package cn.witsky.rtp2ws.client.redis;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.StaticScriptSource;

import cn.witsky.rtp2ws.SpringContextHolder;

public class RedisClient {
	private static StringRedisTemplate redisTemplate;
	
	static {
		redisTemplate=SpringContextHolder.getBean(StringRedisTemplate.class);
	}
	
	public static void set(String key, String value,Long seconds) {
		redisTemplate.opsForValue().set(key, value, seconds,TimeUnit.SECONDS);
	}
	
	public static void set(String key, String value) {
		redisTemplate.opsForValue().set(key, value);
	}
	public static void set(String key, String value,int expire,TimeUnit timeUnit) {
		redisTemplate.opsForValue().set(key, value, expire, timeUnit);
	}
	public static void del(String key) {
		redisTemplate.delete(key);
	}
	public static String get(String key) {
		return redisTemplate.opsForValue().get(key);
	}

	public static void sadd(String key, String member) {
		redisTemplate.opsForSet().add(key, member);
	}
	public static String srandmember(String key) {
		return redisTemplate.opsForSet().members(key).iterator().next();
	}
	public static void sadd(String key, String[] members) {
		redisTemplate.opsForSet().add(key, members);
	}


	public static void hdel(String key, String hashKey) {
		redisTemplate.opsForHash().delete(key, hashKey);
	}

	public static Map<Object, Object> hgetAll(String key) {
		return redisTemplate.opsForHash().entries(key);
		
	}
	public static Object hget(String key,String hashKey) {
		return redisTemplate.opsForHash().get(key, hashKey);
	}
	
	public static void hset(String key,String hashKey,Object value) {
		 redisTemplate.opsForHash().put(key, hashKey, value);
	}
	public static void rpush(String key, String value) {
		redisTemplate.opsForList().rightPush(key, value);
	}

	public static String lpop(String key) {
		return redisTemplate.opsForList().leftPop(key);
	}
	public static Object execLuaScript(String luaScript,Class returnClazz,String... params) {
		DefaultRedisScript defaultRedisScript = new DefaultRedisScript();
		defaultRedisScript.setScriptSource(new StaticScriptSource(luaScript));
		defaultRedisScript.setResultType(returnClazz);
		Object obj=redisTemplate.execute(defaultRedisScript, null, params);
		return obj;
	}

}
